package com.varian.security.model;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.varian.security.constant.SecurityConstant;
import com.varian.tool.enums.UserStatusEnum;
import lombok.Getter;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ben
 * @since 2024/6/24
 */
@Getter
public class LoginUser implements UserDetails, CredentialsContainer {

    private final Long userId;
    private final String username;
    private final String avatar;
    @JsonIgnore
    private String password;
    private final String nickname;
    private final Map<String, Object> extraMap;
    private final Boolean enable;
    private final Set<GrantedAuthority> authorities;

    public LoginUser(Long userId, String username, String avatar, String nickname, Map<String, Object> extraMap, Boolean enable, Collection<String> authorities) {
        this.userId = userId;
        this.username = username;
        this.avatar = avatar;
        this.password = StringPool.HASH;
        this.nickname = nickname;
        this.extraMap = extraMap;
        this.enable = enable;
        this.authorities = CollUtil.isNotEmpty(authorities)
                ? authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toUnmodifiableSet())
                : Collections.emptySet();
    }

    public LoginUser(Long userId, String username, String avatar, String password, String nickname, UserStatusEnum status, Map<String, Object> extraMap, Collection<String> authorities) {
        this.userId = userId;
        this.username = username;
        this.avatar = avatar;
        this.password = password;
        this.nickname = nickname;
        this.extraMap = extraMap;
        this.enable = UserStatusEnum.ENABLE.equals(status);
        this.authorities = CollUtil.isNotEmpty(authorities)
                ? authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toUnmodifiableSet())
                : Collections.emptySet();
    }

    @Override
    public boolean isEnabled() {
        return Boolean.TRUE.equals(enable);
    }

    @Override
    public void eraseCredentials() {
        this.password = null;
    }

    public Long getDeptId() {
        return MapUtil.getLong(this.extraMap, SecurityConstant.EXTRA_KEY_DEPT_ID);
    }

}
